import datetime
import time
from flask import Blueprint, jsonify, request, session, abort
from appserver import to_dict
from admin.core.task import test_go
from models.entity.alarm import Alarm
from models.entity.device import Device
from models.entity.device_with_sensor import DeviceWithSensor
from models.entity.district import District
from models.entity.district_with_facility import DistrictWithFacility
from models.entity.facility import Facility
from models.entity.facility_with_device import FacilityWithDevice
from models.entity.sensor import Sensor
from utils.result import result
import json
mod = Blueprint("core_alarm", __name__, url_prefix="/core/alarm", template_folder="templates", static_folder="static")

@mod.route("/get_alarm/", methods=["GET", "POST"])
def get_alarm():
    return '111'
    # all_points = Point().get_list_all()
    # # print('all_points',all_points)
    # rdic = {}
    # rdic["data"] = []
    # for item in all_points:
    #     #   注意序列化 ,字典和费字典的转换
    #     rdic["data"].append(item.to_dict())
    # return result(data=rdic["data"])

@mod.route('/add/',methods=['GET','POST'])
def add_alarm():
    """添加按钮"""  # 正常
    """
    {
        key:value
    }
    """

    tmp = {}
    data = []
    dict = json.loads(request.data.decode("utf-8"))
    grade = dict.get('grade', '')
    alarm_time = dict.get('alarm_time', '')
    details = dict.get('details', '')
    pump_name = dict.get('pump_name', '')
    device_name = dict.get('device_name', '')
    monitoring = dict.get('monitoring', '')
    reference = dict.get('reference', '')
    type = dict.get('type', '')

    alarm = Alarm()
    alarm.grade = grade
    alarm.alarm_time = alarm_time
    alarm.details = details
    alarm.pump_name = pump_name
    alarm.device_name = device_name
    alarm.monitoring = monitoring
    alarm.reference = reference
    alarm.type = type

    # alarm.to_dict()
    # data.append(alarm.to_dict(dict))
    # data.append(alarm.get_dic())

    # data.append(alarm.get_dic())
    if alarm.save():
        data.append(alarm.get_dic())
        id = alarm.id
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        print(555,data)

        # data.append(alarm.get_dic())

        send = str(id) + '?' + str(grade) + '?' + alarm_time + '?' + details + '?' + pump_name + '?' + device_name + '?' + monitoring + '?' + reference + '?' + str(type) + '?yes'

        test_go(send)
        print(222222)
        return jsonify(tmp)
        print(333333)
    else:
        tmp['success'] = 0
        tmp['error_code'] = -3
        tmp['error_msg'] = "未知错误"
        tmp['data'] = data
        return jsonify(tmp)

@mod.route("/update_alarm/", methods=["GET", "POST"])
def update_alarm():
    #处理报警状态
    """
    {
        id : num
    }
    """
    data = []
    try:
        dict = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")

    alarm = Alarm.get_alarm_by_id(dict['id'])

    try:
        alarm.from_dict(dict)
        # data.append(alarm.get_dic())
    except RuntimeError as e:
        return result(success=0, error_code=-2, error_msg=str(e))

    if alarm.save():
        data.append(alarm.get_dic())
        send = str(dict['id']) + '?' + str(dict['type']) + '?no'
        test_go(send)
        return result(success=1,data=data)
    else:
        return result(success=0, error_code=-3, error_msg="未知错误")


@mod.route("/alarm/",methods=["POST", "GET"])
def alarm():
    """
    模糊查询
    """
    # request: json
    # {
    #      {"Topic":"/1401010010001/M1304","Type":0,"Level":0,"Context":{"Msg":"超限报警,值500.上限450,下限330"},
    #          "SerialId":"1538028110634","Time":"2018-09-27T14:01:50.634325+08:00"}
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    topic = data["Topic"]
    time = data["Time"]
    type = data["Type"]
    level = data["Level"]
    context = data["Context"]["Msg"]
    # print('kkk', type(context))
    serial_id = data["SerialId"]
    print(1111)
    sensor = Sensor.get_sensor_by_topic(topic)
    connectors = DeviceWithSensor.query.filter_by(sensor_id=sensor.id).all()
    for item in connectors:
        device = Device.get_device_by_id(item.device_id)
    connectors = FacilityWithDevice.query.filter_by(device_id=device.id).all()
    for item in connectors:
        facility = Facility.get_facility_by_id(item.facility_id)
    connectors = DistrictWithFacility.query.filter_by(facility_id=facility.id).all()
    for item in connectors:
        district = District.get_district_by_id(item.district_id)
    print(444)
    d = []
    rdic = {}
    rdic["level"] = data["Level"]
    rdic["district_id"] = district.id
    rdic["district_name"] = district.name
    rdic["facility_id"] = facility.id
    print(555)
    rdic["facility_name"] = facility.name
    rdic["device_id"] = device.id
    rdic["device_name"] = device.name
    print(6666)
    # print("1111类型,", type(data["Context"]))
    rdic["context"] = data["Context"]
    print(7777)
    # print("类型,", type(data["Context"]))
    # rdic["time"] = time.strftime("%Y-%m-%d")
    # rdic['start_time'] = self.start_time.strftime("%Y-%m-%d %H:%M:%S")
    rdic["time"] = time.replace('T', " ").split(".")[0]
    # "Time":"2018-09-27T14:01:50.634325+08:00"
    # rdic["time"] = time.strptime(time1,"%Y-%m-%d %H:%M:%S")
    # rdic["time"] = datetime.struct_time(time, "%Y-%m-%d %H:%M:%S")
    # datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z')
    d.append(rdic)
    alarm = Alarm()
    try:
        alarm.topic = topic
        print(22)
        alarm.type = type
        print(33)
        alarm.context = context
        # alarm.context = str(context)
        alarm.level = level
        alarm.serial_id = serial_id
        alarm.time = rdic["time"]
        # data.append(alarm.get_dic())
    except RuntimeError as e:
        return result(success=0, error_code=-2, error_msg=str(e))
    if alarm.save() is False:
        result(success=0, error_code=-1, error_msg="保存错误")
    return result(data=d)





